<template>
  <div class="message-window">
 <div class="title">
    <div class="top-head-image" :style="{backgroundImage:`url(${$store.state.chatObjectHeadImage})`}"></div>
    <p class="top-head-name">{{$store.state.chatObjectName}}</p>
    <div class="top-right-info"></div>
  </div>
    <!-- 聊天展示框 -->
   <div class="chat-body " ref="keepDown">
    <div v-for="(p,index) in chatMsgList" :key="index" class="chat-item" >
        <div v-show="p.senduseruid==$store.state.userUid" class="chat-item-me ">
            <div style="width: 90%; margin: 0% 1% 0% 0%; display: flex; justify-content: flex-end;">
                <p v-if="!p.isimage" style="background-color: #78b922; padding: 2%; display: inline-block; border-radius: 5px; ">{{p.data}}</p>
                    <el-image
                    v-else-if="p.isimage"
                    style=" padding: 2%; background-size: contain; background-repeat: no-repeat; max-width: 35%; max-height: 50vh;"
                    :src="p.data"
                    :preview-src-list="[p.data]"/>
            </div>
            <div class="chat-head-image" :style="{backgroundImage:`url(${$store.state.headImage})`}"/>
            
        </div>

        <div v-show="!(p.senduseruid==$store.state.userUid)" class="chat-item-not-me">
            <div class="chat-head-image" :style="{backgroundImage:`url(${p.senduserheadimage})`}" />
             <div style="width: 90%; margin: 0% 0% 0% 1%;">
                <p v-if="!(p.isimage)" style="background-color: #ffffff; padding: 2%; display: inline-block; border-radius: 5px; ">{{p.data}}</p>
                    <el-image
                    v-else-if="p.isimage"
                    style=" padding: 2%; background-size: contain; background-repeat: no-repeat; max-width: 35%; max-height: 50vh;"
                    :src="p.data"
                    :preview-src-list="[p.data]"/>
            </div>
        </div>
            
    </div>


  </div>

   <div class="chat-input">
    <div class="input-util">
        <el-popover
        class="emoji-shell"
        placement="top"
        width="280"
        trigger="click">

        <div class="emoji-container">
            <!-- 双重循环，简单来说就是外面的渲染了N行，里面的渲染了行内对应列的真实数据 -->
            <!-- 里面的key没用到，主要是给dom识别的，在这里可以无视，保持唯一性即可 -->
          <div
            v-for="(row, rowIndex) in emoji"
            :key="`emoji-${rowIndex}`"
            class="emoji-row-flex"
          >
            <div
              v-for="(emoji, colIndex) in row"
              :key="`emoji-${rowIndex}-${colIndex}`"
              class="emoji-cell"
              @click="handleEmojiClick(emoji)">
              {{ emoji }}
            </div>
          </div>
        </div>
        <div slot="reference" class="emoji-icon"></div>
        </el-popover>
        <!-- 图片发送 -->
        <el-upload
        accept=".jpg, .png"
        class="file-shell"
        action="null"
        :before-upload="BoforeFileUpload"
        :show-file-list="false"
        :on-change="fileChange">
        <el-image style="width: 100%; height: 100%; object-fit: contain;" :src='require("@/assets/image-icon.png")'></el-image>
        </el-upload>
    </div>

    <div class="input-region">
        <textarea v-model="inputData" rows="4" cols="50" ></textarea>
        <div @click="sendMsg" class="send-button">发送</div>
    </div>

  </div>
  </div>
</template>

<script>
export default {
    data(){
        return{
            oldScrollHeight:0, // 控制聊天信息展示位置跳转的
            inputData:"", //
            emoji:[["😊","😂","🤣","😁","😉"],["😎","😀","😜","🤤","🥳"],
            ["😏","😐","😑","🙄","🤖"],["👻","😡","🤡","🤯","🙈"],["😶","🤫","😭","😤","😵"]],
            imageFile:'',
        }
    },
    mounted() {
        this.$nextTick(() => {
            const contentRef = this.$refs["keepDown"];
            contentRef.scrollTop = contentRef.scrollHeight-contentRef.clientHeight;
            this.$store.commit("UPDATE_MESSAGE_OLDSCROLL_HEIGHT",contentRef.scrollHeight)
        });
    },
    computed:{
        chatMsgList(){
            return this.$store.state.chatMsgList;
        }
    },
    updated() {
        // 使用 $nextTick 确保 DOM 完全更新后再滚动
        this.$nextTick(() => {
            const contentRef = this.$refs["keepDown"];
            setTimeout(()=>{
                // 如果当前是再看最新内容，就会在收到内容更新后展示最新消息
                // 如果当前在看历史记录，则不会跳转到最下面的新消息上
                // 这里的+2是因为得到的属性会出现小数，所以考虑最坏结果就多加两个像素位的偏移量保证正常执行
                if(contentRef.scrollTop+contentRef.clientHeight+2>=this.$store.state.messageOldScrollHeight){
                    contentRef.scrollTop = contentRef.scrollHeight-contentRef.clientHeight;
                    this.$store.commit("UPDATE_MESSAGE_OLDSCROLL_HEIGHT",contentRef.scrollHeight)
                }
            },10)
        });
    },
    methods:{
        sendMsgCallback(res){
            if(res.code==200){
                if(res.chathistory.isimage){
                    res.chathistory.data=this.$webSocketTools.base64ToImage(res.chathistory.data)
                }
                this.$store.commit("UPDATE_CHAT_MSG",res.chathistory);
                this.$store.commit("UPDATE_CHAT_LIST",res.chathistory);
                // 清空输入框,并且把展示部分拉到最新位置
                this.inputData=''
                this.$nextTick(() => {
                    const contentRef = this.$refs["keepDown"];
                    contentRef.scrollTop = contentRef.scrollHeight-contentRef.clientHeight;
                    this.$store.commit("UPDATE_MESSAGE_OLDSCROLL_HEIGHT",contentRef.scrollHeight)
                });
                return 
            }else{
                 this.$message({
                    message:res.msg,
                    type:'warning'
                })
            }
        },
        sendMsg(){
            if(!this.$store.state.chatObjectExist){
                this.$message({
                    message:'该用户/群已注销',
                    type:'warning'
                })
                return
            }
            if(this.inputData==''){
                this.$message({
                    message:'发送内容里什么都没有哦!',
                    type:'warning'
                })
                return 
            }
            this.$store.commit('ADD_TASK',this.sendMsgCallback.bind(this))
        
            let proto =new this.$protobufClass.PackageInfo();
            let data = new this.$chatHistory.ChatHistory();
            // 填充数据
            data.setData(this.inputData);
            data.setSenduseruid(this.$store.state.userUid)
            data.setSendusername(this.$store.state.userName)
            // 注意时区,+8小时给中国时间戳
            data.setSenddate((new Date().getTime()+ (8 * 60 * 60 * 1000)).toString());
            // 对群和好友进行不同属性赋值
            if(this.$store.state.chatObjectIsGroup){
                data.setGroupuid(this.$store.state.chatObjectUid)
                data.setGroupname(this.$store.state.chatObjectName)
            }else{
                data.setGetuseruid(this.$store.state.chatObjectUid)
                data.setGetusername(this.$store.state.chatObjectName)
            }
            // 填充并发送
            proto.setChathistory(data);
            proto.setCallbackid(8); // 后端的处理事件id
            proto.setTaskid(this.$store.state.taskId); // 自己的任务id、
            proto=proto.serializeBinary();
            this.$webSocketTools.send(this,proto)
        },
        // 当文件点击上传的时候触发
        BoforeFileUpload(file){
            let fileType =file.type === 'image/jpeg' || file.type==='image/png'
            let size= file.size/1024<800
            if(fileType && size){
                // 在这里组装数据并发送
                this.$store.commit('ADD_TASK',this.sendMsgCallback.bind(this))
        
                let proto =new this.$protobufClass.PackageInfo();
                let data = new this.$chatHistory.ChatHistory();
                // 填充数据
                const reader = new FileReader();
                // 这个是异步的，异步将file对象转为base64字符串，完成后调用下面的onload方法
                reader.readAsDataURL(file);
                // 所有的操作都要在这里进行，因为在外面的话可能异步转换操作还没完时就执行了
                reader.onload = () => {
                    data.setData(reader.result);
                    data.setIsimage(true);
                    data.setSenduseruid(this.$store.state.userUid)
                    data.setSendusername(this.$store.state.userName)
                    // 注意时区,+8小时给中国时间戳
                    data.setSenddate((new Date().getTime()+ (8 * 60 * 60 * 1000)).toString());
                    // 对群和好友进行不同属性赋值
                    if(this.$store.state.chatObjectIsGroup){
                        data.setGroupuid(this.$store.state.chatObjectUid)
                        data.setGroupname(this.$store.state.chatObjectName)
                    }else{
                        data.setGetuseruid(this.$store.state.chatObjectUid)
                        data.setGetusername(this.$store.state.chatObjectName)
                    }
                    // 填充并发送
                    proto.setChathistory(data);
                    proto.setCallbackid(8); // 后端的处理事件id
                    proto.setTaskid(this.$store.state.taskId); // 自己的任务id、
                    proto=proto.serializeBinary();
                    this.$webSocketTools.send(this,proto)
                }
            }else{
                this.$message({
                    message:'图片大小超出800kb或格式不为png、jpg格式',
                    type:'error'
                })
            }
        },
        // 这里检测到改变后直接存储图片文件
        fileChange(file){
            // 如果要动态展示的话就在这里给展示数据赋值
            // 现在不需要动态展示，所以只是做个占位
            // 实际上给发送文件赋值可以直接发数据的时候赋或者直接用里面的file
            this.imageFile=file;
        },
        handleEmojiClick(emoji) {
            this.inputData+=emoji;
        }
    }

}
</script>

<style scoped>
.chat-head-image{
    width: 5%; 
    height: 4.5vh; 
    background-size: contain;
    background-repeat: no-repeat;
}
.chat-item-not-me{
    display: flex;
    width: 60%;
    margin-right: auto;
    border-radius:3px ;
}
.chat-item-me{
    display: flex;
    justify-content: flex-end;
    border-radius:3px ;
    width: 60%;
    margin-left: auto;
}
.chat-item{
    width: 98%;
    margin: 1%;
    word-wrap: break-word; /* 长单词换行 */
    border-radius: 5px;
}
.send-button:hover{
    cursor: pointer;
}
.send-button{
    width: 10%;
    height: 20%; 
    background-color: #78b922;
    border:1px solid #ABACAF ;
    margin-left: 85%;
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center;
    color: #292929;  
    font-size: 0.81vw;
    font-weight: bold;
}
textarea {
    resize: none; /* 禁止调整大小 */
    border: none; /* 移除边框 */
     /*移除焦点状态下的轮廓*/
    outline: none;
    overflow: auto; /* 确保超出的内容可以滚动 */
    padding: 0.5%;
    margin:0.5%; 
    background-color: transparent; /* 设置背景色为透明 */
    width: 98%; 
    height: 50%; 
    font-size:1vw;
    line-height:1.5
}
.file:hover{
    cursor: pointer;
}
.emoji-icon:hover{
    cursor: pointer;
}
.input-region{
    width: 100%;
    height: 82%;
}
.file-shell{
    width: 2.5%;
    height: 70%;
    margin: 0.5% 0% 0% 2%;
    display: flex;
    overflow: hidden;
    }
.emoji-shell{
    width: 3%;
    height: 90%;
    margin: 0.2% 0% 0% 2%;
}
.emoji-icon{
    width: 100%;
    height: 100%;
    background-image: url("@/assets/emoji.png");
    background-size: contain;
    background-repeat: no-repeat;
}
.input-util{
    width: 100%;
    height: 18%;
    display: flex;
}

/* 外部主体格式 */
.emoji-container {
    font-size:1.5vw;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

/* 对每行数据做格式渲染 */
.emoji-row-flex {
  display: flex;
  /* 允许换行 */
  flex-wrap: nowrap;  
  width: 100%;
  justify-content: space-around; /*使每个内容之前及边缘都有相等的空间 */
}

/* 对每个具体的数据做格式渲染 */
.emoji-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  padding: 5px; /* 根据需要调整 */
  border-radius: 5px; /* 可选，为每个emoji单元格添加圆角 */
}
.top-right-info:hover{
    cursor:pointer
}
.top-head-image{
    border-radius: 5px;
    width: 4%;
    height: 80%;
    background-size: contain;
    background-repeat: no-repeat;
    margin: 0.5% 0% 0% 1%;
}
.top-right-info{
    width: 4%;
    background-image: url("@/assets/info.png");
    height: 40%;
    background-size: contain;
    background-repeat: no-repeat;
    margin: 1.5% 0% 0% 40%;
}
.top-head-name{
    width: 50%;
    height: 50%;
    font-size:1.2vw;
    margin: 1.5% 0% 0% 0.8%;
    
}
.message-window{
    display: flex;
    flex-direction:column ;
    width: 75.395vw;
    height: 95.5vh;
    border-radius: 0px 30px 0px 0px;
}
.title{
    border-bottom:1px solid #e2e2e2 ;
    display: flex;
    width: 100%;
    height: 8%;
    border-radius: 0px 30px 0px 0px;
}
.chat-body{
    overflow-y: scroll;
    width: 100%;
    height: 67%;
}
.chat-input{
    width: 100%;
    height: 25%;
    border-top:1px solid #e2e2e2 ;
}
</style>